package com.ysxm.controller.usercontroller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.taglibs.standard.lang.jstl.test.beans.PublicBean1;
import org.apache.tools.ant.types.resources.comparators.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.xdevapi.JsonArray;
import com.ysxm.entity.Comment;
import com.ysxm.entity.Movies;
import com.ysxm.entity.Moviessorrt;
import com.ysxm.entity.User;
import com.ysxm.service.userservice.UserService;
import com.ysxm.util.FileAccepterUtil;
import com.ysxm.util.MD5Util;
import com.ysxm.util.MailUtils;
import com.ysxm.util.MulitPartUtil;
import com.ysxm.util.ResponseInfo;

@Controller
@RequestMapping(value="/user")
public class UserController {
	@Autowired
	private UserService userService;

	// 用户注册
	@RequestMapping(value = "userRegister", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject userRegister(HttpServletRequest request, @RequestBody @Validated User user) {
		JSONObject json = new JSONObject();

		int status = 0;
		String msg = "注册成功";

		/*
		 * if (user.getUsername() == null || user.getUsername().equals("")) {
		 * json.put("status", -1); json.put("msg", "操作失败，用户名不能为空"); return json;
		 * }
		 * 
		 * if (user.getPassword() == null || user.getPassword().equals("")) {
		 * json.put("status", -1); json.put("msg", "操作失败，密码不能为空"); return json;
		 * }
		 * 
		 * if (user.getPhone() == null || user.getPhone().equals("")) {
		 * json.put("status", -1); json.put("msg", "用户电话不能为空"); return json; }
		 * 
		 * if (user.getEmail() == null ||user.getEmail().equals("")) {
		 * json.put("status", -1); json.put("msg", "用户邮箱不能为空"); return json; }
		 * 
		 * if (user.getAddress() == null || user.getAddress().equals("")) {
		 * json.put("status", -1); json.put("msg", "用户地址不能为空"); return json; }
		 */
		try {
			if (!userService.isName(user.getUsername())) {
				json.put("status", -1);
				json.put("msg", "该用户名已注册");
				return json;
			}
			if (!userService.isPhone(user.getPhone())) {
				json.put("status", -1);
				json.put("msg", "该用户电话已注册");
				return json;
			}
			if (!userService.isEmail(user.getEmail())) {
				json.put("status", -1);
				json.put("msg", "该用户邮箱已注册");
				return json;
			}
			if (!user.getPassword().equals(user.getSecondPassword())) {
				json.put("status", -1);
				json.put("msg", "你输入的密码不一致");
				return json;
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", -1);
			json.put("msg", "操作失败,请稍后再试");
			return json;
		}
		user=new User(user.getUsername(),MD5Util.getMd5(user.getPassword()),user.getPhone(),user.getEmail()
				,user.getAddress(),user.getUserhead());
		userService.userRegister(user);
		json.put("status", status);
		json.put("msg", msg);
		json.put("user", user);
		return json;
	}

	// 用户登录
	@RequestMapping(value = "userLogin", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject userLogin(@RequestBody User user, HttpSession session) {
		JSONObject json = new JSONObject();
		int status = 0;
		String msg = "登录成功";
		user = userService.userLogin(user.getUsername(), user.getPassword());
		
		try {
			if (user == null) {
				json.put("status", -1);
				json.put("msg", "用户名或密码错误");
				return json;
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", -1);
			json.put("msg", "操作失败");
			return json;
		}
		session.setAttribute("uid", user.getUid());
		session.setMaxInactiveInterval(30*60);
		json.put("user", user);
		json.put("status", status);
		json.put("msg", msg);
		return json;
	}

	// 用户注销
	@RequestMapping(value = "userLoginOut", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject userLoginOut(HttpSession session) {
		JSONObject json = new JSONObject();
		int status = 0;
		String message = "操作失败，请稍后再试";

		try {
			// 销毁session
			session.invalidate();

			status = 1;
			message = "退出成功";
		} catch (Exception e) {
			e.printStackTrace();
		}

		json.put("status", status);
		json.put("message", message);
		return json;
	}

	// 用户查看个人信息
	@RequestMapping(value = "lookupUser", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject lookuoUser(@RequestBody String uid) {
		System.out.println("uid=" + uid);
		JSONObject json = JSONObject.parseObject(uid);
		int id = Integer.parseInt(json.getString("uid"));
		System.out.println("id=" + id);
		int status = 0;
		String msg = "查看个人信息成功";
		User user = null;
		try {
			user = userService.lookupUser(id);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", -1);
			json.put("msg", "操作失败");
			return json;
		}
		json.put("status", status);
		json.put("msg", msg);
		json.put("user", user);
		return json;
	}

	// 用户修改个人信息
	@RequestMapping(value = "updataUser", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject updateUser(@RequestParam(value = "file", required = false) MultipartFile file, User user,
			HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		int status = 0;
		String msg = "修改成功";
		try {
			/*if (!userService.isName(user.getUsername())) {
				json.put("status", -1);
				json.put("msg", "该用户名已存在");
				return json;
			}
			if (!userService.isPhone(user.getPhone())) {
				json.put("status", -1);
				json.put("msg", "该用户电话已存在");
				return json;
			}
			if (!userService.isEmail(user.getEmail())) {
				json.put("status", -1);
				json.put("msg", "该用户邮箱已存在");
				return json;
			}*/

			String path = request.getServletContext().getRealPath("/upload/");

			FileAccepterUtil accepterUtil = new FileAccepterUtil();
			String fileName = null;
			if (file != null) {
				fileName = accepterUtil.FileUpload(file, path);
			}
			user.setUid(user.getUid());
			user.setUserhead(fileName);
			user.toString();
			userService.updateUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", -1);
			json.put("msg", "操作失败");
			return json;
		}

		json.put("status", status);
		json.put("msg", msg);
		return json;

	}

	// 用户查看影视列表
	@RequestMapping(value = "findAllMovies", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject findAllMovies() {

		JSONObject json = new JSONObject();
		int status = 0;
		String msg = "查看影视成功";
		List<Movies> list = null;
		try {
			list = userService.findAllMovies();
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", -1);
			json.put("msg", "操作失败");
			return json;
		}
		json.put("status", status);
		json.put("msg", msg);
		json.put("list", list);
		return json;
	}

	// 用户查看影视
	@RequestMapping(value = "findMoviesById", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject findMoviesById(@RequestBody JSONObject json) {
        Integer mid=json.getInteger("mid");
		int status = 0;
		String msg = "查看成功";
		Movies movies = null;
		try {
			movies = userService.findMoviesById(mid);
			System.out.println(mid);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", -1);
			json.put("msg", "操作失败");
			return json;
		}
		json.put("status", status);
		json.put("msg", msg);
		json.put("movies", movies);
		return json;
	}

	// 用户查看影视分类
	@RequestMapping(value = "findAllMoviesSort", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject findAllMoviesSort() {
		JSONObject json = new JSONObject();
		int status = 0;
		String msg = "查看成功";
		List<Moviessorrt> moviessorrts = null;
		try {
			moviessorrts = userService.findAllMoviesSort();
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", -1);
			json.put("msg", "操作失败");
			return json;
		}

		json.put("status", status);
		json.put("msg", msg);
		json.put("moviessorrts", moviessorrts);
		return json;
	}

	// 用户查看所属分类下的影视
	@RequestMapping(value = "findMoviesSortById", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject findMoviesSortById(@RequestBody JSONObject json) {
		Integer msid=json.getInteger("msid");
		int status = 0;
		String msg = "查看成功";
		Moviessorrt moviessorrt = null;
		try {
			moviessorrt = userService.findMoviesSortById(msid);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", -1);
			json.put("msg", "操作失败");
			return json;
		}
		json.put("status", status);
		json.put("msg", msg);
		json.put("moviessorrt", moviessorrt);
		return json;
	}

	// 用户通过搜索框查询影视
	@RequestMapping(value = "searchMovies", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject searchMovies(@RequestBody JSONObject json) {
		String moviesname=json.getString("moviesname");
		int status = 0;
		String msg = "搜索成功";
		List<Movies> movies;
		try {
			movies = userService.searchMovies(moviesname);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", -1);
			json.put("msg", "操作失败");
			return json;
		}
		json.put("status", status);
		json.put("msg", msg);
		json.put("movies", movies);
		return json;
	}

	// 用户添加视频收藏
	@RequestMapping(value = "addCollect", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResponseInfo<String> addCollect(@RequestBody JSONObject json) {
		Integer uid=json.getInteger("uid");
		Integer mid=json.getInteger("mid");
		System.out.println(uid);
		userService.addCollect(uid, mid);
		return new ResponseInfo<String>(ResponseInfo.SUCCESS_CODE, "添加成功");
	}

	// 用户查看收藏
	@RequestMapping(value = "lookAllCollect", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResponseInfo<List<Movies>> lookAllCollect(@RequestBody JSONObject json) {
		Integer uid=json.getInteger("uid");
		List<Movies> movies = userService.lookAllCollect(uid);
		return new ResponseInfo<List<Movies>>(ResponseInfo.SUCCESS_CODE, "查看收藏", movies);
	}

	// 用户删除收藏
	@RequestMapping(value = "deleteCollect", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResponseInfo<String> deleteCollect(@RequestBody Map<String, Object> maps) {
		@SuppressWarnings("unchecked")
		ArrayList<Integer> cids = (ArrayList<Integer>) maps.get("cid");
		Integer[] cid = cids.toArray(new Integer[cids.size()]);
		userService.deleteCollect(cid);
		return new ResponseInfo<>(ResponseInfo.SUCCESS_CODE, "删除收藏成功");
	}

	// 添加观看历史
	@RequestMapping(value = "addRecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResponseInfo<String> addaddRecord(@RequestBody JSONObject json) {
		Integer uid=json.getInteger("uid");
		Integer mid=json.getInteger("mid");
		System.out.println(uid);
		userService.addRecord(uid, mid);
		return new ResponseInfo<String>(ResponseInfo.SUCCESS_CODE, "添加成功");
	}

	// 用户查看观看历史
	@RequestMapping(value = "lookAllRecord", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResponseInfo<List<Movies>> lookAllRecord(@RequestBody JSONObject json) {
		Integer uid=json.getInteger("uid");
		List<Movies> movies = userService.lookAllRecord(uid);
		return new ResponseInfo<List<Movies>>(ResponseInfo.SUCCESS_CODE, "查看观看历史", movies);
	}

	// 用户删除观看历史
	@RequestMapping(value = "deleteRecord", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResponseInfo<String> deleteRecord(@RequestBody Map<String, Object> maps) {
		@SuppressWarnings("unchecked")
		ArrayList<Integer> rids = (ArrayList<Integer>) maps.get("rid");
		Integer[] rid = rids.toArray(new Integer[rids.size()]);
		userService.deleteRecord(rid);
		return new ResponseInfo<>(ResponseInfo.SUCCESS_CODE, "删除观看历史成功");
	}

	// 用户发表评论
	@RequestMapping(value = "addComment", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResponseInfo<Object> addComment(@RequestBody Comment comment) {
		comment.setTf("0");
		userService.addComment(comment);
		comment = userService.lookCommentById(comment.getUid(), comment.getCid());
		return new ResponseInfo<Object>(ResponseInfo.SUCCESS_CODE, "发表评论成功", comment);
	}

	// 用户查看自己发表的评论
	@RequestMapping(value = "lookComment", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResponseInfo<List<Comment>> lookComment(@RequestBody JSONObject json) {
		Integer uid=json.getInteger("uid");
		List<Comment> commentnames = userService.lookComment(uid);
		return new ResponseInfo<List<Comment>>(ResponseInfo.SUCCESS_CODE, "查看成功", commentnames);
	}

	// 用户删除评论
	@RequestMapping(value = "deleteComment", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResponseInfo<String> deleteComment(@RequestBody Map<String, Object> maps) {
		@SuppressWarnings("unchecked")
		ArrayList<Integer> cids = (ArrayList<Integer>) maps.get("cid");
		Integer[] cid = cids.toArray(new Integer[cids.size()]);
		userService.deleteComment(cid);
		return new ResponseInfo<>(ResponseInfo.SUCCESS_CODE, "删除评论成功");
	}

	// 用户在评论界面删除评论
	@RequestMapping(value = "deleteCommentById", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResponseInfo<String> deleteCommentById(@RequestBody JSONObject json) {
		Integer uid=json.getInteger("uid");
		Integer cid=json.getInteger("cid");
		userService.deleteCommentById(uid, cid);
		return new ResponseInfo<>(ResponseInfo.SUCCESS_CODE, "删除评论成功");
	}

	// 用户查看一个影视下的所有评论
	@RequestMapping(value = "findAllComment", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResponseInfo<List<Comment>> findAllComment(@RequestBody JSONObject json) {
		Integer mid=json.getInteger("mid");
		List<Comment> comments = userService.findAllComment(mid);
		return new ResponseInfo<List<Comment>>(ResponseInfo.SUCCESS_CODE, "查看成功", comments);
	}

	//发送邮箱
	@RequestMapping(value = "sendEmail", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public void sendEmail(@RequestBody JSONObject json,HttpSession session)
			throws AddressException, MessagingException {
		String email=json.getString("email");
		String code = (int) ((Math.random() * 9 + 1) * 100000) + "";// 生成随机验证码
		session.setAttribute("code", code);// 将验证码存入session
		session.setMaxInactiveInterval(5*60);//设置验证码到期时间为5分钟
		MailUtils.sendMail(email, "您的修改密码验证码是"+code);// 将验证码作为邮件内容参数发送给接收者
	}
	
	// 找回密码
	@RequestMapping(value = "updataPassword", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject updatePassword(@RequestBody JSONObject json, HttpSession session) {
		String email = json.getString("email");
		String password = json.getString("password");
		String secondPassword = json.getString("secondPassword");
		String code = json.getString("code");
		int status = 0;
		String msg = "修改成功";
		//获取保存在session的验证码
		String code2 = (String) session.getAttribute("code");
		//判断验证码是否到期
		if (session.getAttribute("code") != null) {
			//判断用户输入验证码是否与session上的验证码一致
			if (code.equals(code2)) {
				//判断密码与确认密码是否一致
				if (password.equals(secondPassword)) {
					userService.updatePassword(email, secondPassword);
					json.put("status", status);
					json.put("msg", msg);
					return json;
				} else {
					json.put("status", -1);
					json.put("msg", "输入密码不一致");
					return json;
				}
			} else {
				json.put("status", -1);
				json.put("msg", "验证码不正确");
				return json;
			}
		} else {
			json.put("status", -1);
			json.put("msg", "验证码已过期");
			return json;
		}
	}
}

